package cn.edu.lcvc.ebuy_23rj2.web.interceptor;


import cn.edu.lcvc.ebuy_23rj2.model.Admin;
import cn.edu.lcvc.ebuy_23rj2.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginForAdminInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AdminService adminService;
    //在执行控制器以前执行，true就表示通过拦截器验证；false就表示被拦截器拒绝（无法访问控制器）
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result=true;//默认不拦截
        //1.获取当前登录账户信息
        HttpSession session=request.getSession();
        Admin admin=(Admin)session.getAttribute("admin");
        if(admin!=null){//如果说已经登录
            if(!adminService.login(admin.getUsername(),admin.getPassword())){//如果密码已经被修改
                session.removeAttribute("admin");
                result=false;//拒绝登录
            }
        }else{//如果没有登录
            result=false;
        }
        if(result==false){//如果被拒绝访问
            String path = request.getContextPath();
            // 获得项目完全路径（假设你的项目叫ebuy_2023rj4，那么获得到的地址就是http://localhost:8081/ebuy_2023rj4/）:
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/";
            response.sendRedirect(basePath+"jsp/backstage/login.jsp");
        }
        return result;
    }
}
